﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace VxiServer
{
    public class PolLobbyCommunication : TcpCommunication
    {
        protected override int Port
        {
            get { return 51220; }
        }

        protected override byte[] ProccessClientRequest(TcpClient client, byte[] request)
        {
            byte[] buffer = request;
            bool hasRun = false;
            int receiveLength = 0;
            do
            {
                if (buffer[4] == 0x01)
                {
                    byte[] returnVal = new byte[24];
                    returnVal[0] = 0x81;
                    uint time = Convert.ToUInt32(DateTime.Now.Subtract(new System.DateTime(1970, 1, 1)).TotalSeconds);
                    byte[] timeArray = BitConverter.GetBytes(time);
                    Buffer.BlockCopy(timeArray, 0, returnVal, 20, 4);

                    client.Client.Send(returnVal);
                }
                else 
                {
                    bool newChar = buffer[4] != 0x28 ? true : false;

                    Buffer.BlockCopy(new byte[32], 0, buffer, 0, 32);

                    if (!hasRun)
                    {
                        buffer[0] = 0x28;
                        buffer[4] = 0x20;
                        buffer[8] = 1;
                        buffer[11] = 0x7f;

                        if (newChar)
                        {
                            client.Client.Send(buffer.Take(144).ToArray());
                        }
                        else
                        {
                            client.Client.Send(buffer.Take(24).ToArray());
                        }
                    }
                    else
                    {
                        client.Client.Send(buffer.Take(receiveLength).ToArray());
                    }
                    hasRun = true;
                }

                receiveLength = client.Client.Receive(buffer);
            } while (receiveLength > 0);
            
            return null;
        }
    }
}
